package it.gtd.swimpool.controller.resources;

import it.gtd.swimpool.model.business.FriendshipManager;
import it.gtd.swimpool.model.entity.FriendshipRequest;
import it.gtd.swimpool.model.entity.User;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import java.util.Collection;
import java.util.List;

@Stateless
@Path("/")
public class FriendshipResource extends SecuredResource {
    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private FriendshipManager friendshipManager;

    @GET
    @Path("/users/{id}/friends")
    public Collection<User> getUserFriends(
        @PathParam("id") int id
    ){
        User user = entityManager.find(User.class, id);
        return user.getFriends();
    }

    @GET
    @Path("/self/requests")
    public List<FriendshipRequest> getOwnFriendshipRequests(
        @CookieParam(Cookie.SESSION_ID) String sessionId
    ) {
        User caller = checkUser(sessionId);
        List<FriendshipRequest> result = friendshipManager.getRequests(caller);

        return result;
    }

    @POST
    @Path("/users/{id}/requests")
    public void sendRequest(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("id") int id
    ) {
        User caller = checkUser(sessionId);
        User target = entityManager.find(User.class, id);
        friendshipManager.sendRequest(caller, target);
    }

    @DELETE
    @Path("/self/requests/{id}")
    public void processRequest(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("id") int id,
        @QueryParam("accepted") @DefaultValue("false") boolean accepted
    ) {
        User caller = checkUser(sessionId);
        User target = entityManager.find(User.class, id);
        FriendshipRequest request =
            entityManager.createNamedQuery("FriendshipRequest.bySenderTargetIds", FriendshipRequest.class)
                         .setParameter("senderId", target.getId())
                         .setParameter("targetId", caller.getId())
                         .getSingleResult();

        if (accepted) {
            friendshipManager.accept(request);
        } else {
            friendshipManager.decline(request);
        }
    }

    @DELETE
    @Path("/self/friends/{id}")
    public void removeFriend(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("id") int id
    ) {
        User caller = checkUser(sessionId);
        User friend = entityManager.find(User.class, id);
        friendshipManager.removeFriendship(caller, friend);
    }
}
